﻿(function () {
    var myApp = angular.module('MyControllers');

    // 正式考试计划控制器
    myApp.controller('planController', ['$scope', '$http', '$modal', 'examPlanService', 'utils', function ($scope, $http, $modal, service, utils) {
        var srv = service.examPlanSrv;

        $scope.getList = function () {
            srv.getList($scope.planType).success(function (data) {
                $scope.list = data;
            });
        };

        $scope.official = function () {
            $scope.planType = 0;
            $scope.getList();
        };

        $scope.imatate = function () {
            $scope.planType = 1;
            $scope.getList();
        };

        $scope.loadSubject = function(model){
            $modal.open({
                templateUrl: '/App/views/ExamPlan/subjectList.html',
                controller: 'subjectList',
                backdrop: 'static',
                keyboard: false,
                resolve: {
                    params: function () {
                        model.planType = $scope.planType;
                        return model;
                    }
                }
            });
        };

        $scope.official();

        $scope.$root.$on('loadPlanOfficialList', function () {
            $scope.official();
        });
        $scope.$root.$on('loadPlanImitateList', function () {
            $scope.imatate();
        });
    }]);

    // 操作试卷控制器
    myApp.controller('operPaper', ['$scope', '$http', '$modal', 'examPlanService', 'utils', function ($scope, $http, $modal, service, utils) {
        var srv = service.examPaperSrv;

        // 加载考试计划
        $scope.loadBatch = function () {
            $modal.open({
                templateUrl: '/App/views/ExamPlan/loadBatch.html',
                controller: 'loadBatch',
                backdrop: 'static',
                keyboard: false,
                resolve: {
                    params: function () {
                        return $scope.planType;
                    }
                }
            });
        };

        // 本地上传
        $scope.uploadPackage = function () {
            $modal.open({
                templateUrl: '/App/views/ExamPlan/Upload.html',
                controller: 'upload',
                backdrop: 'static',
                keyboard: false,
                resolve: {
                    params: function () {
                        return $scope.planType;
                    }
                }
            });
        };

        // 在线导入
        $scope.importPackage = function () {
            srv.localUpload().success(function (data) {
                    if (data.resultType == 'Success') {
                        utils.notify('导入成功！', 'success');
                    } else {
                        utils.notify(data.message, 'warning');
                    }
            });

            // $modal.open({
            //     templateUrl: '/App/views/ExamPlan/Import.html',
            //     controller: 'import',
            //     resolve: {
            //         params: function () {
            //             return $scope.planType;
            //         }
            //     }
            // });
        };

        // 在线导入
        $scope.importPlanPackage = function () {
            alert(1);
        };

        // 考场管理
        $scope.room = function (model) {
            window.location.href = '#/examRoom/list/' + model.examPlanInfoID + '/' + model.examPlanName;
        };

        // 生成试卷
        $scope.build = function (model) {
            // 判断是否需要配置座位号，如果需要，则跳转到配置界面，如不需要继续
            srv.isRequireSetSeat(model.examPlanInfoID).success(function (data) {
                if (data.resultType == 'Success') {
                    $modal.open({
                        templateUrl: '/App/views/ExamPlan/Build.html',
                        controller: 'build',
                        backdrop: 'static',
                        keyboard: false,
                        size: 'lg',
                        resolve: {
                            params: function () {
                                return model;
                            }
                        }
                    });
                } else {
                    utils.notify(data.message, 'warning');
                    window.setTimeout(function () {
                        window.location.href = '#/examRoom/list/' + model.examPlanInfoID + '/' + model.examPlanName;
                    }, 1000);
                }
            });
        };

        // 查看明细
        $scope.detail = function (model) {
            $scope.loadingState = true;

            var parameter = {
                planId: model.batchId,
                isOfficial: $scope.planType == 0,
                isAnyTime: model.examMode == 3,
                planName: model.examPlanName,
                isGenerated: model.sysState == 6
            };

            utils.encrypt(JSON.stringify(parameter)).success(function (data) {
                if (data.resultType == 'Success') {
                    window.location.href = '#/examPlan/detail' + '?parameter=' + data.appendData;
                } else {
                    utils.notify(data.message, 'warning');
                }

                $scope.loadingState = false;
            });
        };
    }]);

    // 加载考试计划需要的控制器及方法列表
    myApp.controller('loadBatch', ['$scope', '$routeParams', '$modalInstance', 'examPlanService', '$modal', 'utils', 'params', '$filter', function ($scope, $routeParams, $modalInstance, service, $modal, utils, params, $filter) {
        var srv = service.examBatch;

        $scope.$root.$on('loadBatchList', function () {
            $scope.getBatchList();
        });

        var methods = {
            getBatchList: function () {
                srv.getBatchList().success(function (data) {
                    $scope.list = data;
                });
            },
            getPlanProgress: function(model){
                srv.getExamPlanProgress(model.batchId).success(function (data) {
                    if(data.progressKey == ""){
                        $scope.downloadPlan(model);
                    }else{
                        $scope.loadPlanProgress(model);
                    }
                });
            },
            downloadPlan: function(model){
                // model.examplanUrl = "/Users/qil/Documents/Work/be-openexam/e5277df1ecf647ffa285ff7f01eb0e84/3e935a3de0aa4754b01fdd507846b61a/examplan.json";
                srv.downloadPlan(model.deploymentMode, model.examplanUrl).success(function (data) {
                    if(data.ResultType == 'Success'){
                        $scope.loadPlanProgress(model);
                    }else{
                        utils.notify(data.message, 'warning');
                    }
                });
            },
            loadPlanProgress: function(model){
                // 进度提示
                $("body").append('<div id="progressDialog" class="modal fade" tabindex="-1" role="dialog"><div class="modal-dialog"><div class="modal-content">'
                    +'<div class="modal-header"><button type="button" class="close closeModal"><span aria-hidden="true">×</span></button><h4 class="modal-title">正在下载考试计划</h4></div>'
                    +'<div class="modal-body"><div class="row"><form class="form-horizontal"><div class="form-group">'
                    +'<label class="col-sm-4 control-label">下载进度：</label>'
                    +'<div class="col-sm-6" style="height: 15px;border-radius: 10px;background:#f2f2f2;position: relative;margin-top: 9px;">'
                    +'<div id="loadPlanProgress" class="loadPlanProgress" style="height: 100%;border-radius: 10px;background: #16BEB1;position: absolute;left: 0;top: 0;text-align:center;font-size: 12px;color:#FFF;"></div>'
                    +'</div></div></form></div></div>'
                    +'</div></div></div>');

                $('#progressDialog').modal({
                    backdrop: 'static',
                    keyboard: false,
                    modal: true
                }).on('shown.bs.modal', function (e) {
                    $modalInstance.close(true);
                    $(".loadPlanProgress").text("0%");
                    $(".loadPlanProgress").css({"width": "0%"});

                    // 调接口获取加载进度
                    $scope.progressInterval = window.setInterval(function () {
                        srv.getExamPlanProgress(model.batchId).success(function (data) {
                            $(".loadPlanProgress").text(data.progress +"%");
                            $(".loadPlanProgress").css({"width": data.progress +"%"});
                            if(data.progressKey == ""){

                            }else if(data.progress == "100"){
                                clearInterval($scope.progressInterval);
                                $('#progressDialog').modal('hide');

                                $scope.loadSubject(model);
                            }else if(data.progress == "-1"){
                                clearInterval($scope.progressInterval);
                                utils.notify(data.message, 'warning');
                                $('#progressDialog').modal('hide');
                            }
                        });
                    }, 3000);
                });

                $(".closeModal").click(function(){
                    $('#progressDialog').modal('hide');
                })
            },
            loadSubject: function(model){
                $modal.open({
                    templateUrl: '/App/views/ExamPlan/subjectList.html',
                    controller: 'subjectList',
                    backdrop: 'static',
                    keyboard: false,
                    resolve: {
                        params: function () {
                            model.planType = params;
                            return model;
                        }
                    }
                });
            },
            close: function () {
                $modalInstance.close(true);
                clearInterval($scope.progressInterval);

                // 刷新当前界面（根据计划类型决定刷新哪一个列表）
                if (params == 0) {
                    $scope.$emit('loadPlanOfficialList');
                } else {
                    $scope.$emit('loadPlanImitateList');
                }
            }
        };
        angular.extend($scope, methods);

        $scope.getBatchList();
    }]);

    // 科目列表需要的控制器及方法列表
    myApp.controller('subjectList', ['$scope', '$routeParams', '$modalInstance', 'examPlanService', '$modal', 'utils', 'params', '$filter', function ($scope, $routeParams, $modalInstance, service, $modal, utils, params, $filter) {
        var srv = service.examBatch;
        $scope.currentPage = 1;
        $scope.pageSize = 10;
        $scope.successCount = 0;
        $scope.failCount = 0;
        $scope.yuPaperCount = 0;
        $scope.reDownLoad = 0;// 0:首次加载  1:重新加载

        var methods = {
            getSubjectList: function () {
                srv.getSubjectList(params.batchId, $scope.currentPage, $scope.pageSize).success(function (data) {
                    $scope.totalPage = data.totalPage;// 总页数
                    $scope.list = data;
                });
            },
            getPaperProgress: function(){
                srv.getExamPaperProgress(params.batchId).success(function (data) {
                    if(data.ProgressInfo.progressKey == ""){// 后台没有下载任务

                    }else{
                        if(data.ProgressInfo.progress == "100"){
                            $scope.setPaperProgress(data);
                        }else{
                            $scope.loadPaperProgress();
                        }
                    }
                });
            },
            loadPaperProgress: function(){
                $scope.loadingState = $scope.loadingPaper = true;
                $(".loadProgress").show();

                $scope.progressInterval = window.setInterval(function () {
                    srv.getExamPaperProgress(params.batchId, $scope.reDownLoad).success(function (data) {
                        if(data.ProgressInfo.progress == "100"){
                            clearInterval($scope.progressInterval);
                        }else if(data.ProgressInfo.progress == "-1"){
                            clearInterval($scope.progressInterval);
                            utils.notify(data.ProgressInfo.message, 'warning');
                        }

                        $scope.setPaperProgress(data);
                        $scope.getSubjectList();
                    });
                }, 3000);
            },
            setPaperProgress: function(data){
                $(".loadProgress").show();
                $scope.progress = data.ProgressInfo.progress;
                $(".loadPaperProgress").text($scope.progress +"%");
                $(".loadPaperProgress").css({"width": $scope.progress +"%"});

                $scope.successCount = 0;
                $scope.failCount = 0;
                $scope.yuPaperCount = 0;

                angular.forEach(data.Count, function (item) {
                    // 试卷下载状态  0:未下载   1:加载完成未生成试卷(失败)   2:下载成功   3:下载失败
                    switch (item.SubjectPaperStatus) {
                        case 0:
                            $scope.yuPaperCount = item.Count;
                            break;
                        //case 1:
                        //    $scope.failCount = item.Count;
                        //    break;
                        case 2:
                            $scope.successCount = item.Count;
                            break;
                        case 3:
                            $scope.failCount = item.Count;
                            break;
                    }
                });
                $(".successPaperNum em").text($scope.successCount);
                $(".failPaperNum em").text($scope.failCount);
                $(".yuPaperNum em").text($scope.yuPaperCount);

                if($scope.progress == "100" && $scope.failCount == 0 && $scope.yuPaperCount == 0 ){
                    $scope.loadingState = true;
                    $scope.loadingPaper = false;
                }
                if($scope.progress == "100" && ($scope.failCount >= 1 || $scope.yuPaperCount >= 1) ){
                    $scope.loadingState = $scope.loadingPaper = false;
                    $(".loadPaper").hide();
                    $(".reloadPaper").show();
                    $scope.reDownLoad = 1;
                }
            },
            downloadPaper: function(){
                srv.downLoadSubjectPaper(params.batchId).success(function (data) {
                    if(data.resultType == 'Success'){
                        $scope.loadPaperProgress(params);
                    }else{
                        utils.notify(data.message, 'warning');
                    }
                });
            },
            // 跳转页
            selectPage: function(){
                //不能小于1大于最大
                if ($scope.currentPage < 1) $scope.currentPage = 1;
                if ($scope.currentPage > $scope.totalPage) $scope.currentPage = $scope.totalPage;
                $scope.getSubjectList();
            },
            // 上一页
            Previous: function(){
                if($scope.currentPage > 1){
                    $scope.currentPage--;
                    $scope.getSubjectList();
                }
            },
            // 下一页
            Next: function(){
                if($scope.currentPage < $scope.totalPage){
                    $scope.currentPage++;
                    $scope.getSubjectList();
                }
            },
            close: function () {
                $modalInstance.close(true);
                clearInterval($scope.progressInterval);
                $scope.$emit('loadBatchList');// 刷新计划列表

                // 刷新当前界面（根据计划类型决定刷新哪一个列表）
                if (params.planType == 0) {
                    $scope.$emit('loadPlanOfficialList');
                } else {
                    $scope.$emit('loadPlanImitateList');
                }
            }
        };
        angular.extend($scope, methods);

        $scope.getPaperProgress();
        $scope.getSubjectList();
    }]);

    // 上传需要的控制器及方法列表
    myApp.controller('upload', ['$scope', '$routeParams', '$modalInstance', 'examPlanService', 'utils', 'params', '$filter', function ($scope, $routeParams, $modalInstance, service, utils, params, $filter) {
        var srv = service.uploadSrv;

        var methods = {
            uploading: function () {
                utils.notify('正在上传中，请等待！', 'success');
            },
            upload: function () {
                $scope.loadingState = true;

                var uploadInterval = window.setInterval(function () {
                    $scope.uploading();
                }, 5000);

                // 提交
                document.uploadForm.submit();

                // 循环获取结果
                var uploadResultInterval = window.setInterval(function () {
                    var result = $("#uploadResult").contents().find("body").html();
                    result = $(result).html();
                    if (result) {
                        $scope.loadingState = false;
                        window.clearInterval(uploadInterval);
                        window.clearInterval(uploadResultInterval);

                        var responseData = JSON.parse(result);
                        if (responseData.ResultType == 'Success') {
                            $('#UploadResult').show().siblings().hide();

                            $('#txtSubjectCount').empty().text(responseData.data.subjectList.length);
                            $('#txtPlanName').empty().text(responseData.data.examPlanInfo.examPlanName);
                            $('#txtExamMode').empty().val(responseData.data.examMode);

                            // 显示科目列表数据
                            var objSubjects = $('#txtSubjects');
                            objSubjects.empty();
                            for (var i = 0; i < responseData.data.subjectList.length; i++) {
                                var curTxt = objSubjects.text();
                                if (i != 0)
                                    curTxt += '、';
                                curTxt += responseData.data.subjectList[i].subjectName;

                                objSubjects.text(curTxt);
                            }

                            // 显示场次列表数据
                            var objScenes = $('#txtExamScenes');
                            objScenes.empty();

                            for (var i = 0; i < responseData.data.examScenesList.length; i++) {
                                var curTxt = objScenes.text();
                                if (i != 0)
                                    curTxt += '、';
                                curTxt += responseData.data.examScenesList[i].examSceneName;

                                objScenes.text(curTxt);
                            }
                        } else {
                            alert(responseData.message);
                        }
                    }
                }, 1000);

                /* 旧的上传方法1
                var options = {
                    type: 'post',
                    semantic: true,
                    success: function (responseData) {
                        responseData = JSON.parse(responseData);

                        $scope.loadingState = false;
                        window.clearInterval(uploadInterval);

                        data = responseData;

                        if (data.ResultType == ResultType.Success) {
                            $('#UploadResult').show().siblings().hide();

                            $('#txtSubjectCount').empty().text(data.data.SubjectList.length);
                            $('#txtPlanName').empty().text(data.data.ExamPlanInfo.ExamPlanName);
                            $('#txtExamMode').empty().val(data.data.examMode);

                            // 显示科目列表数据
                            var objSubjects = $('#txtSubjects');
                            objSubjects.empty();
                            for (var i = 0; i < data.data.SubjectList.length; i++) {
                                var curTxt = objSubjects.text();
                                if (i != 0)
                                    curTxt += '、';
                                curTxt += data.data.SubjectList[i].SubjectName;

                                objSubjects.text(curTxt);
                            }

                            // 显示场次列表数据
                            var objScenes = $('#txtExamScenes');
                            objScenes.empty();

                            for (var i = 0; i < data.data.ExamScenesList.length; i++) {
                                var curTxt = objScenes.text();
                                if (i != 0)
                                    curTxt += '、';
                                curTxt += data.data.ExamScenesList[i].ExamSceneName;

                                objScenes.text(curTxt);
                            }
                        } else {
                            alert(data.Message);
                        }
                    }
                };

                jQuery_1_8_3('#uploadForm').ajaxSubmit(options);
                */

                /* 旧的上传方法2
                var requestData = new FormData();
                var files = $('#uploadify').get(0).files;
                if (files.length > 0)
                    requestData.append("uploadFile", files[0]);

                var ajaxRequest = $.ajax({
                    type: "POST",
                    url: "Manager/ExamPlan/LocalUpload/",
                    contentType: false,
                    processData: false,
                    data: requestData,
                    dataType: 'json'
                });

                ajaxRequest.done(function (responseData, textStatus) {
                    $scope.loadingState = false;
                    window.clearInterval(uploadInterval);

                    data = responseData;

                    if (data.ResultType == ResultType.Success) {
                        $('#UploadResult').show().siblings().hide();

                        $('#txtSubjectCount').empty().text(data.data.SubjectList.length);
                        $('#txtPlanName').empty().text(data.data.ExamPlanInfo.ExamPlanName);
                        $('#txtExamMode').empty().val(data.data.examMode);

                        // 显示科目列表数据
                        var objSubjects = $('#txtSubjects');
                        objSubjects.empty();
                        for (var i = 0; i < data.data.SubjectList.length; i++) {
                            var curTxt = objSubjects.text();
                            if (i != 0)
                                curTxt += '、';
                            curTxt += data.data.SubjectList[i].SubjectName;

                            objSubjects.text(curTxt);
                        }

                        // 显示场次列表数据
                        var objScenes = $('#txtExamScenes');
                        objScenes.empty();

                        for (var i = 0; i < data.data.ExamScenesList.length; i++) {
                            var curTxt = objScenes.text();
                            if (i != 0)
                                curTxt += '、';
                            curTxt += data.data.ExamScenesList[i].ExamSceneName;

                            objScenes.text(curTxt);
                        }
                    } else {
                        alert(data.Message);
                    }
                });
                */
            },
            afterUpload: function () {
                $scope.close();

                var mode = $('#txtExamMode').val();

                // 刷新当前界面（根据计划类型决定刷新哪一个列表）
                if (mode == 0) {
                    $scope.$emit('loadPlanOfficialList');
                } else {
                    $scope.$emit('loadPlanImitateList');
                }
            },
            close: function () {
                $modalInstance.close(true);
            }
        };
        angular.extend($scope, methods);
    }]);

    // 导入需要的控制器及方法列表
    myApp.controller('import', ['$scope', '$routeParams', '$modalInstance', 'examPlanService', 'utils', 'params', '$filter', function ($scope, $routeParams, $modalInstance, service, utils, params, $filter) {
        var methods = {
            importPackage: function () {

            },
            close: function () {
                $modalInstance.close(true);
            }
        };
        angular.extend($scope, methods);
    }]);

    // 生成试卷需要的控制器及方法列表
    myApp.controller('build', ['$scope', '$routeParams', '$modalInstance', 'examPlanService', '$modal', 'utils', 'params', '$filter', function ($scope, $routeParams, $modalInstance, service, $modal, utils, params, $filter) {
        var srv = service.examPaperSrv, planId = params.examPlanInfoID;

        $scope.examMode = params.examMode;

        var methods = {
            getPaperList: function () {
                srv.getPaperList(planId).success(function (data) {
                    $scope.list = data;

                    // 判断是否显示批量操作按钮
                    $scope.isBatch = data != null && data.length > 0;
                });
            },
            clean: function (model) {
                if (model.examMode != 3) {
                    $scope.loadingState = true;
                    srv.checkBeforeClean(planId, model.examSubjectId).success(function (data) {

                        $scope.loadingState = false;
                        if (data.resultType == 'Success') {
                            $scope.openClean(params, model);
                        } else {
                            utils.notify(data.message, 'warning');
                        }
                    });
                } else {
                    $scope.openClean(params, model);
                }
            },
            checkAll: function () {
                var isCheck = $('.table :checkbox:first').is(':checked');

                $('.table :checkbox').not(':first').each(function () {
                    $(this).prop('checked', $(this).is(':disabled') ? false : isCheck);
                });
            },
            check: function (model) {
                var cbx = $('#cbxSubject_' + model.examSubjectId);
                cbx.prop('checked', cbx.is(':disabled') ? false : !cbx.is(':checked'));
            },
            build: function (model) {
                $scope.check(model);

                var loading = $('#loading_' + model.examSubjectId);
                $scope.loadingState = true;
                loading.show();

                srv.generationPaper(planId, model.examSubjectId).success(function (data) {
                    if (data.resultType == 'Success') {
                        // 生成后刷新当前页面
                        $scope.getPaperList();
                        utils.notify('生成《' + model.examSubjectName + '》试卷成功！', 'success');
                    } else {
                        utils.notify(data.message, 'warning');
                    }

                    $scope.loadingState = false;
                    loading.hide();
                });
            },
            buildBatch: function () {
                $scope.loadingState = $scope.loadingBatch = true;

                var selList = [];
                angular.forEach($scope.list, function (data, index, array) {
                    var cbx = $('#cbxSubject_' + data.examSubjectId);

                    if (cbx.is(':checked') && !cbx.is(':disabled')) {
                        selList.push(data);
                    }
                });

                if (selList.length <= 0) {
                    utils.notify('请选择一项进行生成试卷操作！', 'warning');
                    $scope.loadingState = $scope.loadingBatch = false;
                } else {
                    // 存储已生成的科目数
                    var generationCount = 0;
                    angular.forEach(selList, function (data, index, array) {
                        var loading = $('#loading_' + data.examSubjectId);
                        loading.show();

                        // TODO: Angularjs方式不能做到Http同步请求，造成页面禁用状态异常
                        $.ajax({
                            async: false,
                            type: 'post',
                            url: '/ExamPlan/GenerationPaperBitch/',
                            data: { planId: planId, subjectId: data.examSubjectId },
                            success:function (resultData) {
                                generationCount++;

                                if (resultData.resultType == 'Success') {
                                    // 生成后刷新当前页面
                                    $scope.getPaperList();
                                    loading.hide();

                                    utils.notify('生成《' + data.examSubjectName + '》试卷成功！', 'success');
                                } else {
                                    utils.notify(resultData.message, 'warning');
                                }

                                if (selList.length == generationCount) {
                                    utils.notify('所选试卷已全部生成成功！', 'success');
                                    $scope.loadingState = $scope.loadingBatch = false;
                                }
                            }
                        });
                    });
                }
            },
            close: function () {
                $modalInstance.close(true);

                // 刷新当前界面（根据计划类型决定刷新哪一个列表）
                if (params.ExamPlanType == 0) {
                    $scope.$emit('loadPlanOfficialList');
                } else {
                    $scope.$emit('loadPlanImitateList');
                }
            },
            openClean: function (plan, subject) {
                $modal.open({
                    templateUrl: '/App/views/ExamPlan/Clean.html',
                    controller: 'clean',
                    backdrop: 'static',
                    keyboard: false,
                    resolve: {
                        params: function () {
                            return { plan: plan, subject: subject };
                        }
                    }
                });
            }
        };
        angular.extend($scope, methods);

        $scope.getPaperList();

        $scope.$root.$on('reloadList', function () {
            $scope.getPaperList();
        });
    }]);

    // 明细需要的控制器及方法列表
    myApp.controller('planDetailController', ['$scope', '$location', '$http', '$modal', 'examPlanService', 'utils', function ($scope, $location, $http, $modal, service, utils) {
        var params, srv = service.detailSrv;

        var methods = {
            init: function () {
                $scope.loadingState = true;
                utils.decrypt($location.$$search.parameter).success(function (data) {
                    if (data.resultType == 'Success') {
                        params = JSON.parse(data.appendData);

                        $scope.isOfficial = params.isOfficial;
                        $scope.isAnyTime = params.isAnyTime;
                        $scope.planName = params.planName;

                        $scope.isGenerated = params.isGenerated;
                        $scope.generatedTitle = params.isGenerated ? '可以生成考生账号' : '当前计划未生成试卷，不能生成考生账号！';

                        $scope.getSceneList();
                        $scope.getRoomList();
                        $scope.getSubjectList();

                        $scope.loadDetailGrid();
                    } else {
                        utils.notify(data.message, 'warning');
                    }

                    $scope.loadingState = false;
                });
            },
            getSceneList: function (roomId, subjectId, current) {
                var defaultData = { examSceneID: null, examSceneName: '全部场次' };

                if (!$scope.isAnyTime) {
                    srv.getSceneList(params.planId, roomId, subjectId).success(function (data) {
                        angular.forEach(data, function (item) {
                            item.examSceneName += ' (' + utils.formatDate(item.planBeginTime) + ')';
                        });

                        data.unshift(defaultData);

                        $scope.sceneList = data;
                        $scope.curScene = current ? current : $scope.sceneList[0];
                    });
                }
                $scope.curScene = [defaultData];
            },
            getRoomList: function (sceneId, subjectId, current) {
                var defaultData = { examRoomID: null, examRoomName: '全部考场' };

                if (!$scope.isAnyTime) {
                    srv.getRoomList(params.planId, sceneId, subjectId).success(function (data) {
                        data.unshift({ examRoomID: null, examRoomName: '全部考场' });

                        $scope.roomList = data;
                        $scope.curRoom = current ? current : $scope.roomList[0];
                    });
                }
                $scope.curRoom = [defaultData];
            },
            getSubjectList: function (sceneId, roomId, current) {
                srv.getSubjectList(params.planId, sceneId, roomId).success(function (data) {
                    data.unshift({ examSubjectID: null, subjectName: '全部科目' });

                    $scope.subjectList = data;
                    $scope.curSubject = current ? current : $scope.subjectList[0];
                });
            },
            // 修改了场次
            //changeScene: function () {
            //},
            // 修改了考场
            //changeRoom: function () {
            //},
            // 修改了科目
            //changeSubject: function () {
            //},
            //change: function () {
            //    var curScene = $scope.curScene;
            //    var curRoom = $scope.curRoom;
            //    var curSubject = $scope.curSubject;

            //    $scope.getSceneList(curRoom.ExamRoomID, curSubject.ExamSubjectID, curScene);
            //    $scope.getRoomList(curScene.ExamSceneID, curSubject.ExamSubjectID, curRoom);
            //    $scope.getSubjectList(curScene.ExamSceneID, curRoom.ExamRoomID, curSubject);

            //    $scope.loadDetailGrid(curScene.ExamSceneID, curRoom.ExamRoomID, curSubject.ExamSubjectID);
            //},
            query: function () {
                var curScene = $scope.curScene;
                var curRoom = $scope.curRoom;
                var curSubject = $scope.curSubject;

                $scope.loadDetailGrid(curScene.examSceneID, curRoom.examRoomID, curSubject.examSubjectID);
            },
            loadDetailGrid: function (sceneId, roomId, subjectId) {
                srv.getDetailList(params.planId, sceneId, roomId, subjectId).success(function (data) {
                    $scope.list = data;

                    $('[data-toggle="tooltip"]').tooltip();
                    setTimeout(function () { $('[data-toggle="tooltip"]').tooltip(); }, 1000);
                    setTimeout(function () { $('[data-toggle="tooltip"]').tooltip(); }, 2000);
                });
            },
            buildAccounts: function (model) {
                $modal.open({
                    templateUrl: '/App/views/ExamPlan/BuildAccounts.html',
                    controller: 'buildAccounts',
                    backdrop: 'static',
                    keyboard: false,
                    resolve: {
                        params: function () {
                            return model;
                        }
                    }
                });
            }
        };

        $scope.$root.$on('afterBuild', function () {
            $scope.query();
        });

        angular.extend($scope, methods);

        $scope.init();
    }]);

    // 生成账号需要的控制器及方法列表
    myApp.controller('buildAccounts', ['$scope', '$routeParams', '$modalInstance', 'examPlanService', 'utils', 'params', '$filter', function ($scope, $routeParams, $modalInstance, service, utils, params, $filter) {
        var model = params, srv = service.detailSrv;
        $scope.headerText = '生成考生账号';

        var methods = {
            build: function () {
                if ($('form#buildForm').valid()) {
                    $scope.loadingState = true;
                    srv.buildAccounts($scope.count, model.examPlanInfoID, model.subjectID, model.examSceneID, model.examRoomID).success(function (data) {
                        $scope.list = data;
                        $scope.headerText = '已生成考生账号';
                        $scope.studentCount = data.length;
                        $scope.loadingState = false;
                        $scope.result = true;
                    });
                }
            },
            close: function () {
                // 之后刷新列表
                $scope.$emit('afterBuild');

                $modalInstance.close(true);
            }
        };
        angular.extend($scope, methods);
    }]);

    // 清理需要的控制器及方法列表
    myApp.controller('clean', ['$scope', '$routeParams', '$modalInstance', 'examPlanService', 'utils', 'params', '$filter', function ($scope, $routeParams, $modalInstance, service, utils, params, $filter) {
        var srv = service.cleanSrv, plan = params.plan, subject = params.subject;

        $scope.examMode = plan.examMode;

        var methods = {
            init: function () {
                // ExamMode：统考1，预考2，随考3
                if ($scope.examMode == 3) {
                    $scope.loadingState = true;
                    srv.getMoniterStatus(plan.examPlanInfoID, subject.examSubjectId).success(function (data) {
                        $scope.loadingState = false;
                        if (data.resultType == 'Success') {
                            $scope.AppendData = data.appendData;
                        } else {
                            utils.notify(data.message, 'warning');
                        }
                    });
                }
            },
            save: function () {
                $scope.loadingState = true;
                srv.cleanPaper(plan.examPlanInfoID, subject.examSubjectId).success(function (data) {
                    $scope.loadingState = false;
                    if (data.resultType == 'Success') {
                        // 之后刷新列表
                        $scope.$emit('reloadList');
                        utils.notify('清理《' + subject.examSubjectName + '》试卷成功！', 'success');
                        $scope.close();
                    } else {
                        utils.notify(data.message, 'warning');
                    }
                });
            },
            close: function () {
                $modalInstance.close(true);
            }
        };
        angular.extend($scope, methods);

        $scope.init();
    }]);
})();